<template>
	<view>
		<view class="coreshop-flex coreshop-flex-direction card">
			<view slot="body" class="coreshop-flex coreshop-flex-direction" style="padding:10rpx 20rpx;">
				<view class="coreshop-flex coreshop-justify-between plan-field-box coreshop-padding" @click="bindShowTextarea('1')">
					<u--textarea
						v-if="textareaIsShow"
						focus
						@blur="bindShowTextarea('')" 
						autoHeight
						height="40"
						:clearable="false"
						maxlength="-1"
						border="none"
						class="coreshop-flex-sub"
						:custom-style="{fontSize:'32rpx'}"
						placeholder="请输入计划事项"
						placeholder-style="font-size:26rpx;color:#999"
						v-model="planItem.JHFL">
					</u--textarea>
					<view v-else class="coreshop-flex-sub textarea-view">
						<text :class="planItem.JHFL?'':'placeholder'">{{planItem.JHFL || '请输入计划事项'}}</text>
					</view>
					
					<view class="del-box" @click="delItem" v-if="type=='add'">
						<u-icon
							name="trash" 
							custom-prefix="custom-icon" 
							color="#999999"
							size="23">
						</u-icon>
					</view>
				</view>
				<template v-if="planItem.JHXQList && planItem.JHXQList.length>0">
					<view class="coreshop-flex coreshop-justify-between c-m-t-10" v-for="(items,idx) in planItem.JHXQList" :key="idx">
						<view class="coreshop-flex coreshop-justify-between coreshop-flex-sub detail-field-box" @click="ifShowArea(idx)">
							<u--textarea
								v-if="focus==idx"
								@blur="ifShowArea2(idx)"
								focus
								autoHeight
								height="40"
								:clearable="false"
								maxlength="-1"
								border="none"
								class="coreshop-flex-sub"
								:custom-style="{fontSize:'32rpx'}"
								placeholder="请输入计划详情"
								placeholder-style="font-size:26rpx;color:#999"
								v-model="planItem.JHXQList[idx].text">
							</u--textarea>
							<view v-else class="coreshop-flex-sub textarea-view">
								<text :class="planItem.JHXQList[idx].text ? '' :'placeholder'">{{planItem.JHXQList[idx].text || '请输入计划详情'}}</text>
							</view>
						</view> 
						<view class="detail-del-icon" v-if="idx=='0'" @click="addDetailItem()">
							<u-icon name="plus" :bold="true"></u-icon>
						</view>
						<view class="detail-del-icon" v-else @click="delDetailItem(idx)">
							<u-icon name="minus" :bold="true"></u-icon>
						</view>
					</view>
				</template> 
				
				<view class="coreshop-flex" v-if="planInfo.JHLX==4">
					<view class="select-sale-type u-flex" @click="showSaleType = true">
						<view class="u-flex-1 sale-type-name" :class="planItem.JHSLLX?'active':''">{{planItem.JHSLLX || '计划类型'}}</view>
						<u-icon :name="showSaleType?'arrow-up':'arrow-down'" color="#999999"></u-icon>
					</view>
					<view class="u-flex-1 u-flex sales-box">
						<input class="u-flex-1 sales-input"
							:value="planItem.Sales || ''"
							maxlength="-1"
							type="number"
							:clearable="false"
							placeholder="请输入计划数量"
							placeholder-style="font-size:24rpx;color:#999"
							:data-idx="index"
							@input="salesInput"/>
							<view>{{planItem.JHSLLX ? $common.getTextFromID(planItem.JHSLLX,typeList) : ''}}</view>
					</view>
				</view>
				
				<view class="coreshop-flex coreshop-align-center detail-icon">
					<view class="detail-icon-list coreshop-flex-sub" hover-class="none" @click="showSelectClient = true">关联客户</view>
					<view class="detail-icon-list coreshop-flex-sub" hover-class="none" @click="showSelectCorrelation = true">关联人员</view>
					<view class="detail-icon-list coreshop-flex-sub" @click="selectPlanTime()">完成时间</view>
				</view>
			</view>
			<view slot="foot">
				<view class="tip" v-if="$common.longDateFormate(planItem.CompletionTime) || planItem.glkhList.length || planItem.glrList.length">
					<plan-correlation :info="{
						time: planItem.CompletionTime,
						glkh: planItem.glkhList,
						glr: planItem.glrList
					}"></plan-correlation>
				</view>
				<view class="coreshop-flex">
					<block v-if="type=='edit'">
						<view class="coreshop-flex-sub deal-btn" @click="cancleEdit">取消</view>
						<view class="coreshop-flex-sub deal-btn btn-sure" @click="editSure">保存</view>
					</block>
					<block v-else>
						<view class="coreshop-flex-sub deal-btn btn-sure" @click="publishItem">确认发布</view>
					</block>
				</view>
			</view>
		</view>
		<!-- 关联人 -->
		<template v-if="showSelectCorrelation">
			<u-popup :show="showSelectCorrelation" mode="right" :customStyle="popupStyle">
				<select-correlation :list.sync="planItem.glrList" :showModel.sync="showSelectCorrelation"></select-correlation>
			</u-popup>
		</template>
		
		<template v-if="showSelectClient">
			<u-popup :show="showSelectClient" mode="right" :customStyle="popupStyle">
				<select-client :item.sync="planItem" :showModel.sync="showSelectClient"></select-client> 
			</u-popup>
		</template>
		
		<!-- 选择计划完成时间 -->
		<u-datetime-picker  
			ref="datetimePicker"
			:show="selectPlanTimeShow"
			v-model="defaultPlanItemTime"
			mode="datetime"
			:formatter="formatter"
			@cancel="dtCancel"
			@confirm="selectPlanItemConfirm">
		</u-datetime-picker>
		
		<!-- <u-select v-model="showSaleType" :list="planSaleTypeList" cancel-text="清空" @confirm="selectPlanSaleType" @cancel="cancelPlanSaleType"></u-select> -->
	</view>
</template>

<script>
	
	import selectCorrelation from '@/pages/member/agent/components/selectCorrelation/index.vue';
	import selectClient from '@/pages/member/agent/components/selectClient/index.vue';
    import planCorrelation from '@/pages/member/agent/components/planCorrelation/index-new.vue';
	
	export default{
		data(){
			return{
				popupStyle:{
					top:'11%',
					width:'100vw'
				},
				planItem:{
					key:'',
					ID:'',
					JHFL:'',
					JHXQList:[{id:'',text:''}],
					CompletionTime:'',
					RowID:'',
					glkhList:[],
					glkh_me:[],
					glke_sub:{},
					glr:[],
					glrList:[],
					Sales:0,
					JHSLLX:'',
				},//事项信息
				delList:[],//要删除的事项id
				
				showSelectCorrelation:false,//关联人员
				showSelectClient:false,//关联客户
				
				selectPlanTimeShow:false,//完成时间选择picker
				defaultPlanItemTime: Number(new Date()),//默认时间
				
				textareaIsShow:false,
				focus:null,
				
				showSaleType:false, 
			}
		},
		components:{
			selectCorrelation,
			selectClient,
			planCorrelation
		},
		computed: {
			planSaleTypeList({$store}){
				return $store.state.planSaleTypeList
			},
			typeList({$store}){
				const planSaleTypeList = $store.state.planSaleTypeList || [];
				let typeList = [];
				planSaleTypeList.forEach(item=>{
					typeList.push({
						id: item.CodeName,
						text: item.Remark
					})
				})
				return typeList;
			}
		},
		props:{
			userData:{
				type:Object,
				default:{}
			},
			planInfo:{
				type:Object,
				default:{}
			},
			item:{
				type:Object,
				default:{}
			},
			type:{
				type:String,
				default:'edit'
			},
			addRowList:{
				type:Array,
				default:[]
			}
		},
		created() {
			const info = this.item || {};
			if(info.jhxq){
				this.planItem.ID = (info.jhxq || {}).id || '';
				this.planItem.JHFL = (info.jhxq || {}).jhfl || '';
				this.planItem.CompletionTime = (info.jhxq || {}).completionTime || '';
				this.planItem.RowID = (info.jhxq || {}).rowID || '';
			}
			
			let glr = info.glr || [] , glrList = [];
			glr.forEach(item=>{
				glrList.push({
					id:item.glr,
					name:item.glrname,
					type:item.glrtype || item.glrtype=='0' ? item.glrtype : '1'
				})
			})
			this.planItem.glrList = glrList;
		
			const glkh = info.glkh || [];
			let GLKHList = [],GLKHList_ME=[],GLKHList_SUB={};
			glkh.forEach(items=>{
				let d = {id:items.glkh,name:items.glkhname};
				GLKHList.push(d);
				if(items.glssr == this.userData.ID){
					GLKHList_ME.push(d);
				}else{
					GLKHList_SUB.id = items.glssr;
					GLKHList_SUB.list = [];
					GLKHList_SUB.list.push(d);
				}
			})
			this.planItem.glkhList = GLKHList;
			this.planItem.glkh_me = GLKHList_ME;
			this.planItem.glkh_sub = GLKHList_SUB;
			
			const list = info.jhxqitems || [];
			let JHXQList = [];
			list.forEach(item=>{
				JHXQList.push({
					id: item.jhxqitem.id,
					text: item.jhxqitem.jhxq,
					rowID:item.jhxqitem.rowID
				});
			})
			if(JHXQList.length){
				this.planItem.JHXQList = JHXQList;
			}
			
			if(info.key){
				this.planItem.key = info.key;
			}
			
			console.log(this.planItem)
			
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		methods:{
			formatter(type, value) {
			     if (type === 'year') {
			         return `${value}年`
			     }
			     if (type === 'month') {
			         return `${value}月`
			     }
			     if (type === 'day') {
			         return `${value}日`
			     }
			     return value
			 },
			salesInput(e){
				const str = e.detail.value.replace(/[^\d]/g,'');
				const strN = str ? str*1 : str;
				this.planItem.Sales = strN;
				return strN;
			},
			selectPlanSaleType(e){
				this.planItem.JHSLLX = e[0].label;
			},
			cancelPlanSaleType(){
				this.planItem.JHSLLX = '';
				this.planItem.Sales = 0;
			},
			//确认修改
			editSure(){
				const d = this.planItem;
				const JHXQList = (d.JHXQList || []).filter(item=>item.text || item.id);
				if(!d.JHFL){
					return uni.showToast({
						title:'请输入计划事项！',
						icon:'none'
					})
				}
				if(JHXQList.length==0){
					return uni.showToast({
						title:'请至少添加一条计划详情！',
						icon:'none'
					})
				}
				if(d.Sales && !d.JHSLLX){
					return uni.showToast({
						title:'请选择计划数量类型！',
						icon:'none'
					})
				}
				
				/* // let jhxq = [],jhxqid = [];
				// JHXQList.forEach(item=>{
				// 	jhxqid.push(item.id);
				// 	jhxq.push(item.text);
				// }) 
				// let detail = {
				// 	JHFL:d.JHFL,
				// 	JHXQ:jhxq.join('|'),
				// 	JHXQID: jhxqid.join('|'),
				// 	JHXQDelID: this.delList.join(','),
				// 	Sales:d.Sales,
				// 	JHSLLX:d.JHSLLX || '',
				// 	CompletionTime : d.CompletionTime,
				// 	OldJHID:'',
				// 	JHZT:'1',
				// 	QKSM:'',
				// 	XCBFSJ:'',
				// 	ActualAmount:0,
				// 	RelationalSchemaID:'',
				// 	GLR: d.glrList || [],
				// 	GLKH: d.glkhList || [],
				// 	ROWID:d.RowID || ''
				// }
				// let params = {
				// 	JHID : this.planInfo.ID,
				// 	XQID : d.ID,
				// 	JHXQ : JSON.stringify([detail]),
				// };
				// console.log(detail)
				// console.log(params) */
				
				
				let field={}; //匹配PC端传递的参数
				field.planDetails = [];
				//明细
				field.planDetailItems = []; 
				field.ID = this.planInfo.ID; 
				field.IsFB = false;
				
				let details = {
				    ID: d.ID,
				    JHFL: d.JHFL,
				    RowID: d.RowID
				};
				field.planDetails.push(details);
				
				let GLR =d.glrList.length > 0 ? d.glrList.map(c=>c.id).join("|") : ""; 
				let diRowId=0;
				JHXQList.forEach(item=>{
					let id=item.id!="" ? item.id : Date.now().toString(36); 
					if(item.rowID!=""){ 
						diRowId=item.rowID;
					}else{
						diRowId=(+diRowId) +1; 
					}
					
					let detailItems = {
					    ID: id,
					    JHXQ: item.text,
						XQID: d.ID,
					    CompletionTime: new Date(this.planItem.CompletionTime),
					    GLR: GLR,
					    GLKH: d.glkhList.length > 0 ? d.glkhList[0].id : "",
					    GLKHName: d.glkhList.length > 0 ? d.glkhList[0].name : "",
					    RowID: diRowId
					}
					field.planDetailItems.push(detailItems);
				})
				
				console.log(field)
				uni.showModal({
					content:'确认修改此条事项?',
					success:e=>{
						if(e.confirm){
							uni.showLoading({
								title:'加载中',
								mask:true
							})
							this.$u.api.editByJHXQ(field).then(res=>{
								uni.hideLoading();
								if (!res.status) {
									this.$u.toast(res.msg) 
								}else{
									uni.showToast({
										title:'操作成功！',
										mask:true
									})
									setTimeout(()=>{
										this.$emit('Cancel');
										this.$emit('Sure');
									},1000)
								}
							}).catch(()=>{
								
							})
						}
					}
				})
				
			},
			cancleEdit(){
				this.$emit('Cancel');
			},
			addDetailItem(){
				this.planItem.JHXQList.push({id:'',text:''});
			},
			delDetailItem(cur){
				const info = this.planItem.JHXQList[cur];
				if(info.id){
					this.delList.push(info.id);
				}
				this.planItem.JHXQList.splice(cur,1);
			},
			//选择完成时间
			selectPlanTime(){  
				this.selectPlanTimeShow = true;
				if(this.planItem.CompletionTime!=""){ 
					this.$refs.datetimePicker.innerValue=this.$common.longDateFormate(this.planItem.CompletionTime)
				}
			},
			selectPlanItemConfirm(e){  
				//const dataTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}`;
				this.planItem.CompletionTime = this.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM'); 
				this.dtCancel();
			},
			dtCancel(){
				this.selectPlanTimeShow = false;
			},
			
			bindShowTextarea(i){
				if(i){
					this.textareaIsShow = true;
				}else{
					this.textareaIsShow = false;
				}
			},
			ifShowArea(idx){
				this.focus = idx + '';
			},
			ifShowArea2(idx){
				setTimeout(()=>{
					const a = this.focus;
					if(a==idx){
						this.focus = null;
					}
				},50)
			},
			delItem(){
				this.$emit('delItem');
			},
			//确认发布
			publishItem(){
				const d = this.planItem;
				const detailList = (d.JHXQList || []).filter(item=>item.text);
			
				if(!d.JHFL){
					return uni.showToast({
						title:'请输入计划事项！',
						icon:'none'
					})
				}
				if(detailList.length==0){
					return uni.showToast({
						title:'请至少添加一条计划详情！',
						icon:'none'
					})
				}else if(this.planItem.CompletionTime==null){
					return uni.showToast({
						title:'请选择完成时间！',
						icon:'none'
					})
				}
				
				d.JHXQList = detailList;
				uni.showModal({
					title:'提示',
					content:'确认添加此条事项？',
					success:res=>{
						if(res.confirm){ 
							// let jhxq = [];
							// detailList.forEach(item=>{
							// 	jhxq.push(item.text);
							// })
							
							// let detail = {
							// 	ROWID: this.addRowList.length+1,
							// 	GLR : d.glrList || [],
							// 	GLKH : d.glkhList || [],
							// 	JHFL:d.JHFL,
							// 	JHXQ : jhxq.join('|'),
							// 	Sales:d.Sales,
							// 	JHSLLX:d.JHSLLX || '',
							// 	CompletionTime : d.CompletionTime,
							// 	OldJHID:'',
							// 	JHZT:'1',
							// 	QKSM:'',
							// 	XCBFSJ:'',
							// 	ActualAmount:0,
							// 	RelationalSchemaID:'',
							// }

							// let params = {
							// 	JHID : this.planInfo.ID,
							// 	JHXQ : JSON.stringify([detail]),
							// };

							uni.showLoading({
								title:'加载中',
								mask:true
							})
							
							let field={}; //匹配PC端传递的参数
							field.planDetails = [];
							//明细
							field.planDetailItems = []; 
							field.ID = 0;
							field.IsFB = false; 
							field.GZJH=this.planInfo.gzjh;
							field.JHLX=1;
							
							 let id = Date.now().toString(36);
							 let rowId=this.addRowList.length+1;
							 let details = {
							     ID: id,
							     JHFL: d.JHFL,
							     RowID: rowId
							 };
							 field.planDetails.push(details);
							 
							 let GLR =d.glrList.length > 0 ? d.glrList.map(c=>c.id).join("|") : ""; 
							 detailList.forEach(item=>{
							 	  let detailItems = {
							 	      ID: id,
							 	      JHXQ: item.text,
							 	      CompletionTime: new Date(this.planItem.CompletionTime),
							 	      GLRName: GLR,
							 	      GLKH: d.glkhList.length > 0 ? d.glkhList[0].id : "",
							 	      GLKHName: d.glkhList.length > 0 ? d.glkhList[0].title : "",
							 	      RowID: `${this.addRowList.length+1}${rowId++}`
							 	  }
							 	  field.planDetailItems.push(detailItems);
							 })
							
							console.log(field)
							this.$u.api.addGZJHXQ(field).then((res) => {
								uni.hideLoading();
								if (!res.status) {
									this.$u.toast(res.msg) 
								}else{
									uni.showToast({
										title:'操作成功！',
										mask:true
									})
									setTimeout(()=>{
										this.$emit('publishSure');
										this.$emit('delItem');
									},1000)
								}
							})
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.del-box{
		width: 39rpx;
		height: 39rpx;
		background-color: #F1F1F5;
		border-radius: 50%;
		text-align: center;
		line-height: 30rpx;
		margin-left: 40rpx;
		margin-top: 6rpx;
	}
	.textarea-view{
		min-height: 40rpx;
		padding: 12rpx 0;
		line-height: 38rpx;
		color: #303133;
		font-size: 32rpx;
	}
	.plan-field-box{
		padding: 0 10rpx;
	}
	.detail-field-box{
		background-color: #F1F1F5;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		&>text{
			min-height: 56rpx;
		}
	}
	.select-sale-type{
		width: 180rpx;
		background: #F1F1F5;
		border-radius: 20rpx;
		padding: 0 20rpx;
		line-height: 80rpx;
		margin-left: 5rpx;
		margin-right: 10rpx;
		color: #7A808A;
		.sale-type-name{
			text-align: center;
			white-space:nowrap;
			overflow:hidden;
			text-overflow:ellipsis;
			color: #999;
			&.active{
				color: #303133;
			}
		}
	}
	.sales-box{
		background: #F1F1F5;
		border-radius: 20rpx;
		margin: 0 5rpx;
		padding: 0 20rpx;
		// line-height: 80rpx;
		height: 80rpx;
		color: $core-type-primary-dark;
		.sales-input{
			width: 100%;
			padding: 10rpx;
			color: #303133;
			height: 60rpx;
			line-height: 60rpx;
			display: block;
		}
	}
	
	.detail-icon{
		line-height: 46rpx;
		font-size: 26rpx;
		color: $core-type-primary-dark;
		text-align: center;
		margin-top: 20rpx;
		margin-bottom: 6rpx;
		.detail-icon-list{
			border-right: 1px solid rgba($color: #E5E5E5, $alpha: 0.5);
			&:nth-last-child(1){
				border: none;
			}
		}
	}
	.tip{
		font-size: 24rpx;
		color: #333;
		line-height: 40rpx;
		padding: 10rpx 20rpx;
	}
	.deal-btn{
		line-height: 80rpx;
		text-align: center;
		color: $core-type-primary-dark;
		border-top: 1px solid $core-type-primary-dark;
		border-bottom-left-radius: 16rpx;
		border-bottom-right-radius: 16rpx;
	}
	.btn-sure{
		background: $core-type-primary-dark;
		color: #fff;
	}
	
	.detail-del-icon{
		width: 80rpx;
		height: 80rpx;
		background-color: #F1F1F5; 
		line-height: 80rpx;
		border-radius: 50%;
		margin-left: 4rpx;
		display: flex;
		justify-content: center;
	}
	
	.add-detail{
		width: 300rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		margin: 10rpx auto;
		border-radius: 10rpx;
		font-size: 24rpx;
		background-color: #666;
		color: #fff;
	}
	
	.card{
		border: 1px solid #F7F7F7;background-color: #FFFFFF;border-radius:16rpx;min-height: 330rpx;
	}
</style>
